package cc.rengu.igas.channel.upqc.core.service.trans;

import cc.rengu.igas.channel.upqc.common.constant.UpqcParamConstant;
import cc.rengu.igas.channel.upqc.common.constant.UpqcTreeNodeConstant;
import cc.rengu.igas.channel.upqc.common.enums.RespCodeEnum;
import cc.rengu.igas.channel.upqc.common.util.UpqcSecurityUtil;
import cc.rengu.igas.channel.upqc.core.model.ChnlBizResponse;
import cc.rengu.igas.channel.upqc.core.service.base.NoticeService;
import cc.rengu.igas.channel.upqc.facade.request.C2BAddDealRequest;
import cc.rengu.igas.channel.upqc.facade.response.C2BAddDealResponse;
import cc.rengu.igas.share.facade.request.UpqcC2bAddDealRequest;
import cc.rengu.igas.share.facade.response.UpqcC2bAddDealResponse;
import cc.rengu.igas.share.facade.result.Result;
import cc.rengu.oltp.service.common.dao.CertInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.CertInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.CertInfo;
import cc.rengu.oltp.service.common.entity.SecPlanInfo;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSONArray;

import java.security.interfaces.RSAPrivateKey;
import java.util.List;
import java.util.Optional;

/**
 * 银联二维码发起附加处理服务
 * BizStatus：
 * 01-业务处理中
 * 40-授权未完成【待密码认证】
 * 41-授权已完成【密码验证完成】
 * <p>
 * 订单表字段：
 * remark1：预授权状态
 * remark2：二维码类型
 * remark3：付款人信息
 * front_seq_num前端流水号：付款凭证号
 */
public class C2BAddDealService extends NoticeService {

    @Override
    protected Object beforeBizProcess() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        CertInfo encryptCertInfo;
        String payerInfo;
        C2BAddDealRequest c2BAddDealRequest = new C2BAddDealRequest();
        ConvertUtil.convertOutput(c2BAddDealRequest);
        //解密付款方信息
        String encoding = UpqcParamConstant.UTF_8_ENCODING;
        /* 获取敏感信息解密证书 */
        String secPlanInfoListString = xmlTreeUtil.getXmlTreeStringValue(UpqcTreeNodeConstant.SEC_PLAN_INFO_LIST);
        List<SecPlanInfo> secPlanInfoList = JSONArray.parseArray(secPlanInfoListString, SecPlanInfo.class);
        Optional<SecPlanInfo> encryptSecPlanOpt = secPlanInfoList.stream().filter(item -> item.getSecPlanType().equals(UpqcParamConstant.DECRYPT_CERT_TYPE)).findFirst();
        if (encryptSecPlanOpt.isPresent()) {
            CertInfoMapper certInfoMapper = new CertInfoMapperImpl();
            encryptCertInfo = certInfoMapper.selectCertInfoByPrimaryKey(encryptSecPlanOpt.get().getInstId() + encryptSecPlanOpt.get().getSecPlanId() + encryptSecPlanOpt.get().getSecPlanType());
        } else {
            rglog.error("");
            throw new BizException(RespCodeEnum.GET_KEY_INFO_ERROR.getRespCode(), RespCodeEnum.GET_KEY_INFO_ERROR.getRespDesc());
        }
        if ("0".equals(encryptCertInfo.getCertSaveType())) {
            payerInfo = UpqcSecurityUtil.decryptData(c2BAddDealRequest.getPayerInfoStr(), encryptCertInfo.getCertValue(), encoding);
        } else {
            List<String> aliasList = RSAUtil.getCertAliasFromPfxCertFile(encryptCertInfo.getCertSavePath(), encryptCertInfo.getCertPassword());
            RSAPrivateKey privateKey = RSAUtil.getPrivateKeyFromPfxCertFile(encryptCertInfo.getCertSavePath(), aliasList.get(0), encryptCertInfo.getCertPassword());
            payerInfo = UpqcSecurityUtil.decryptData(c2BAddDealRequest.getPayerInfoStr(), privateKey, encoding);
        }
        rglog.debug("payerInfo=[{}]", payerInfo);
        c2BAddDealRequest.setPayerInfoStr(payerInfo);
        return c2BAddDealRequest;
    }

    @Override
    protected ChnlBizResponse callBizService(Object request) throws Exception {
        C2BAddDealRequest c2BAddDealRequest = (C2BAddDealRequest) request;
        C2BAddDealResponse c2BAddDealResponse = new C2BAddDealResponse();
        c2BAddDealResponse.setHeader(c2BAddDealResponse.getHeader());

        /* 调用Share模块中的银联二维码业务公共处理服务 */
        UpqcC2bAddDealRequest upqcC2bAddDealRequest = new UpqcC2bAddDealRequest();
        BeanUtil.beanCopy(c2BAddDealRequest, upqcC2bAddDealRequest);
        upqcC2bAddDealRequest.getHeader().setTxnNum("T00SH004");
        upqcC2bAddDealRequest.getHeader().setTraceNo(ChannelEnum.UPQC.getChannelType() + DateUtil.getCurrentDateTime("yyyyMMddHHmmssSSS") + RandomUtil.randomNumStr(10));
        DubboService dubboService = new DubboServiceImpl();
        Result<UpqcC2bAddDealResponse> callResult = (Result<UpqcC2bAddDealResponse>) dubboService.callDubboService("upqcUnifiedService", "c2bAddDeal", upqcC2bAddDealRequest);
        if (null != callResult) {
            UpqcC2bAddDealResponse upqcC2bAddDealResponse = callResult.getResult();
            BeanUtil.beanCopy(upqcC2bAddDealResponse, c2BAddDealResponse);
        }

        /* 组装应答报文 */
        ChnlBizResponse chnlBizResponse = new ChnlBizResponse();
        chnlBizResponse.setResult(c2BAddDealResponse);
        return chnlBizResponse;
    }

    @Override
    protected void afterBizProcess(ChnlBizResponse response) throws Exception {
        C2BAddDealResponse c2BAddDealResponse = (C2BAddDealResponse) response.getResult();
        ConvertUtil.convertInput(c2BAddDealResponse);
    }
}
